import Taro, { Component } from '@tarojs/taro'
import { Input, Text, View } from '@tarojs/components'
import styles from './index.module.scss'
import classNames from 'classnames'
// import './index.scss'

interface IProps {
  min: number
  max: number
  value: any
  onChange: Function
}

/**
 * 商品数量输入框
 */
export default class GoodsNumber extends Component<IProps, {}> {
  props: any

  static options = {
    addGlobalClass: true
  }

  //  点击按钮
  private handleClick(clickType: 'minus' | 'plus', e): void {
    const { value } = this.props
    const deltaValue = clickType === 'minus' ? -1 : 1
    let newValue = Number(value) + deltaValue
    newValue = this.verifyRange(newValue)
    this.props.onChange(newValue, e)
  }

  //  验证范围
  private verifyRange(value: number) {
    const { max, min } = this.props
    return (value < min) ? min : ((value > max) ? max : value)
  }

  //  input 输入 change 事件
  private handleInput = (e) => {
    const { value } = e.target
    const { disabled } = this.props
    if (disabled) return
    let newValue = /^\+?[1-9][0-9]*$/.test(value) ? Number(value) : 1
    newValue = this.verifyRange(newValue)

    this.props.onChange(newValue, e)
    return {
      value: newValue
    }
  }

  render() {
    const { min, max, value } = this.props
    const inputValue = this.verifyRange(Number(value))
    const prefixCls = 'goods-number'
    const minusBtnCls = classNames(styles[`${prefixCls}__btn`], 'f-g-5', {
      [styles[`${prefixCls}--disabled`]]: inputValue <= min
    })
    const plusBtnCls = classNames(styles[`${prefixCls}__btn`], 'f-g-5', {
      [styles[`${prefixCls}--disabled`]]: inputValue >= max
    })
    return (<View className={styles[prefixCls]}>
      <View
        className={minusBtnCls}
        onClick={this.handleClick.bind(this, 'minus')}
      >
        <Text className='bnn-icon goods-number__btn-icon goods-number__btn-minus'>&#xe7fd;</Text>
      </View>
      <Input
        type='number'
        value={value}
        className={styles[`${prefixCls}__input`]}
        onInput={this.handleInput}
      />
      <View
        className={plusBtnCls}
        onClick={this.handleClick.bind(this, 'plus')}
      >
        <Text className='bnn-icon goods-number__btn-icon goods-number__btn-add'>&#xe8fe;</Text>
      </View>
    </View>)
  }
}
